<?php


namespace app\index\controller;

/**
 * 测试socket
 * Class SocketTest
 * @package app\index\controller
 */
// 解决中文乱码
header("Content-type:text/html;charset=utf-8");

class SocketTest
{

    public $IP = "127.0.0.1";
    public $PORT = "8080";

    /**
     * 服务端
     */
    public function server()
    {
        error_reporting(E_ALL);
        // 设置无限请求超时时间
        set_time_limit(0);
        // 解决中文乱码
        header("Content-type:text/html;charset=utf-8");
        echo "服务端\n";
        // 创建socket
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($socket < 0) {
            echo "socket_create失败，原因：" . socket_strerror($socket) . "\n";
            exit();
        }
        // 把socket绑定到ip地址上
        $res = socket_bind($socket, $this->IP, $this->PORT);
        if ($res < 0) {
            echo "socket_bind失败，原因：" . socket_strerror($res) . "\n";
            exit();
        }
        // 监听指定socket的所有连接
        if ($res = socket_listen($socket, 4) < 0) {
            echo "socket_listen失败，原因：" . socket_strerror($res) . "\n";
            exit();
        }
        // 次数
       // $count = 0;
        do {
            // 接收socket连接
            $msgSocket = socket_accept($socket);
            if ($msgSocket < 0) {
                echo "socket_accept失败，原因：" . socket_strerror($msgSocket) . "\n";
                break;
            }
            // 发送数据给客户端
            $msg = "测试成功，hello Client$count \n";
            socket_write($msgSocket, $msg, strlen($msg));
            echo "server 测试成功了";
            // 获取客户端数据
            $sub = socket_read($msgSocket, 2048);
            echo "收到客户端消息：$sub\n";
            // 第五次结束
          /*  if (++$count >= 5) {
                break;
            }*/
            // 关闭socket
            socket_close($msgSocket);
        } while (true);
        // 关闭socket
        socket_close($socket);
    }

    /**
     * 客户端
     */
    public function client()
    {

        error_reporting(E_ALL);
        // 设置无限请求超时时间
        set_time_limit(0);
        echo "客户端\n";
        // 创建socket
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($socket < 0) {
            echo "socket_create失败，原因：" . socket_strerror($socket) . "\n";
            exit();
        }

        // 连接socket
        $res = socket_connect($socket, $this->IP, $this->PORT);
        if ($res<0) {
            echo "socket_connect失败，原因：" . socket_strerror($res) . "\n";
            exit();
        }
        // 写数据
        $in = "测试成功，hello client";
        if (!socket_write($socket, $in, strlen($in))) {
            echo "socket_write失败，原因：" . socket_strerror($socket) . "\n";
            exit();
        }
        echo "客户端发送消息给服务端成功！\n";
        // 读取指定长度的数据
        while ($out = socket_read($socket, 2048)) {
            echo "接收服务端消息成功！" . $out;
        }
        // 关闭socket
        socket_close($socket);
        echo "关闭socket成功！\n";
    }
}
